package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.common.ResultInfo;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    //分页查询
    @GetMapping("/dish/page")
    //接收前端参数  自定义参数初始值
    public ResultInfo getPage(String name, @RequestParam(value = "page",defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
        //调用service 并传入三个参数 生成page 对象返回前端
       Page page= dishService.getPage(name,pageNum,pageSize);
        return ResultInfo.success(page);
    }
//    添加方法 增删改需要变更数据需要吧redis中的数据重新删除才能覆盖
    @PostMapping("/dish")
    public ResultInfo save(@RequestBody Dish dish){
        //创建对应的键
        String key="dish_"+dish.getCategoryId();
        //调用redis删除方法
        redisTemplate.delete(key);
      dishService.save(dish);
      return ResultInfo.success(null);
    }
    //查找id 方法
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        //调用查询id方法
       Dish dish= dishService.findById(id);
       return ResultInfo.success(dish);
    }
    //更新方法
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish){
        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.update(dish);
        return ResultInfo.success(null);
    }
    //删除方法
    @DeleteMapping("/dish")
    public ResultInfo delete(Long[] ids){
        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        if (ids != null && ids.length > 0) {
            dishService.delete(ids);
        }
        return ResultInfo.success(null);
    }
    //禁用
    @PostMapping("/dish/status/{status}")
    public ResultInfo setStatus(@PathVariable("status")Integer type,Long[] ids){
        //因为这个操作同时会影响多个菜品,所以需要将Redis中的所有菜品都删除
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        if (ids != null && ids.length > 0) {
            dishService.setStatus(type, ids);
        }
        return ResultInfo.success(null);
    }
    //根据菜品id回显 确定套餐是被启用的
    @GetMapping("/dish/list")
    public  ResultInfo getList(Long categoryId,@RequestParam(defaultValue = "1") Integer status,String name){
       List<Dish> dishList= dishService.getList(categoryId,status,name);
       return ResultInfo.success(dishList);
    }


}
